package com.example.demo_text;

import java.io.IOException;

import user.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String passwordAgain = request.getParameter("password_again");
        String email = request.getParameter("email");
        int age = Integer.parseInt(request.getParameter("age"));

        // ✅ 改成 userType
        String userType = request.getParameter("userType"); // 注意字段名要和 register.jsp 中的一致

        if (!password.equals(passwordAgain)) {
            request.setAttribute("error", "两次密码输入不同");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        if (UserDAO.checkUsernameExists(username)) {
            request.setAttribute("error", "用户名已存在");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        User user = UserDAO.registerUser(username, password, passwordAgain, email, age, userType);

        if (user != null) {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);

            // 根据用户类型进行跳转
            if ("admin".equalsIgnoreCase(user.getUserType())) {
                response.sendRedirect("AdmitHome.jsp"); // 管理员页面
            } else {
                response.sendRedirect("home.jsp"); // 学生默认跳转 home.jsp
            }

        } else {
            request.setAttribute("error", "注册失败，请稍后再试");
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }

    }

}
